//
//  XMGKeyboardTextView.swift
//  01-封装表情键盘
//
//  Created by xiaomage on 15/12/12.
//  Copyright © 2015年 xiaomage. All rights reserved.
//

import UIKit

class XMGKeyboardTextView: UITextView {

    func insertEmoticon(emoticon : XMGKeyboardEmoticon) {
        // 1.emoji表情的图文混排
        if let tempEmojiStr = emoticon.emoticonStr {
            // 1.1.取出光标所在的位置
            let range = selectedTextRange!
            
            // 1.2.用emoji表情替换光标所在的位置
            replace(range, withText: tempEmojiStr)
            
            return
        }
        
        // 2.新浪的图片的图文混排
        if let tempPngPath = emoticon.pngPath {
            
            // 2.1.通过statusTextView中的文字创建属性字符串
            let attrMStr = NSMutableAttributedString(attributedString: attributedText)
            
            // 2.2.创建图片的属性字符串
            let attachment = XMGKeyboardAttachment()
            attachment.emoticonChs = emoticon.chs
            let fontHeight = font!.lineHeight
            attachment.bounds = CGRect(x: 0, y: -4, width: fontHeight, height: fontHeight)
            attachment.image = UIImage(contentsOfFile: tempPngPath)
            let imageAttrStr = NSAttributedString(attachment: attachment)
            
            // 2.3.获取光标所在的位置
            let range = selectedRange
            
            // 2.4.将光标所在位置的字符串进行替换
            attrMStr.replaceCharacters(in: range, with: imageAttrStr)
            // 2.5.显示可变属性字符串即可
            attributedText = attrMStr
            
            // 2.6.确定光标的位置,光标放在插入图片的后面
            selectedRange = NSRange.init(location: range.location + 1, length: 0)
            
            // 2.7.重新设置的大小
            font = UIFont.systemFont(ofSize: 18)
            
            return
        }
        
        // 3.删除最近一个字母或者表情
        if emoticon.isRemoveButton {
            deleteBackward()
        }
    }
    
    func emoticonStr() -> String {
        // 1.获取整个字符串的range
        let range = NSRange(location: 0, length: attributedText.length)
        
        // 2.创建可变字符串(之后将取出的字符串和表情拼接到可变字符串中)
        var strM = String()
        
        // 3.遍历属性字符串
        attributedText.enumerateAttributes(in: range, options: NSAttributedString.EnumerationOptions.init(rawValue: 0)) { (dict: [String : Any], range: NSRange, _) in
            if let tempAttachment = dict["NSAttachment"] as? XMGKeyboardAttachment {
                strM += tempAttachment.emoticonChs!
            } else {
                strM += (self.text as NSString).substring(with: range)
            }
        }
        
        
        return strM
    }
}
